package net.xdclass.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.LoginUser;

import java.util.Date;

@Slf4j
public class JwtUnit {
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 10;

    private static final String SECRET = "xdclass.net";

    private static final String TOKEN_PREFIX = "xdclass1024shop";

    private static final String SUBJECT = "xdclass";

    public static String getJwt(LoginUser loginUser) {
        if (loginUser == null){
            throw new NullPointerException("loginUser对象为空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", loginUser.getHeadImg())
                .claim("name", loginUser.getName())
                .claim("id", loginUser.getId())
                .claim("mail", loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimeStamp() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    public static Claims checkJwt(String token){
        try{
            Claims body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return body;
        }catch (Exception e){
            log.info("jwt token解析失败");
            return null;
        }
    }

}
